/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/14 22:25
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
(function () {

    var api = {
        "getConfigUrl": '/goods/lists/getConfigs',
        "saveThumbUrl": '/general/general/upload?width=320&height=180',
        "saveUrl": '/goods/lists/saveGoods',
        "editUrl": '/goods/lists/editGoods',
        "getItemUrl": '/goods/lists/getGoodsInfo'
    };

    sm.controller('admin-goods-add-controller', ['$scope', '$http', 'Modal', function ($scope, $http, Modal) {

        var ue = UE.getEditor('container', {
            'autoClearinitialContent' : false,
            'toolbars' : [['fullscreen', 'source', 'preview', '|', 'bold', 'italic', 'underline', '|',
                'justifyleft', 'justifycenter', 'justifyright', '|', 'insertorderedlist', 'insertunorderedlist', 'blockquote', 'emotion',
                'link', 'removeformat', 'simpleupload', 'insertimage', '|', 'paragraph', 'fontsize',
                'inserttable']],
            'elementPathEnabled' : false,
            'initialFrameHeight': 250,
            'focus' : false,
            'maximumWords' : 999999,
            'zIndex': 999
        });

        $scope.units = [];
        $scope.cats = [];
        $scope.bases = [];
        $scope.baseName = '';
        $scope.selectVideo = false;
        $scope.thumbView = '';
        $scope.bannerThumbView = '';
        $scope.recommendThumbView = '';
        $scope.thumbLists = [];
        $scope.selectExpType = 1;

        $scope.detail = {
            goodsName: '',
            description: '',
            categoryId: 0,
            bannerThumb: '',
            recommendThumb: '',
            thumb: '',
            thumbWidth: 0,
            thumbHeight: 0,
            liveUrl: '',
            unit: '个',
            stars: 5,
            content: '',
            expType: '',
            expAmount: null,
            activity: false
        };

        $scope.pageType = 'add';
        $scope.goodsId = 0;
        $scope.stars = [1, 2, 3, 4, 5];
        var bak = angular.copy($scope.detail);
        var streamBak = angular.copy($scope.stream);

        $scope.catsOpt = [];
        $scope.parentsOpt = [];
        $scope.getLabel = function (id, k) {
            var name = '';
            angular.forEach($scope.parentsOpt, function (v) {
                if (v.id == id) {
                    name = v.name
                }
            });
            return name;
        };

        $scope.rules = [];
        $scope.ruleItem = {
            id: null,
            ruleName: '',
            ruleStore: '',
            ruleOldPrice: '',
            ruleNewPrice: '',
            rulePurchaserPrice: '',
            ruleGoodsWeight: '',
            ruleExpressWeight: ''
        };
        var ruleBak = angular.copy($scope.ruleItem);

        (function () {
            $http.get(api.getConfigUrl).success(function (res) {
                $scope.units = res.unit;
                $scope.cats = res.cat;
                $scope.bases = res.bases;

                angular.forEach(res.cat, function (val) {
                    if (val.parentId != 0) {
                        $scope.catsOpt.push(val);
                    } else {
                        $scope.parentsOpt.push(val);
                    }
                });

                // 检查
                getItem();
            });
        })();

        function getItem() {

            var search = window.location.search;
            if (!search) {
                return false;
            }

            var goodsId = GetQueryString('goodsId');

            if (!goodsId) {
                return false;
            }

            $scope.pageType = 'edit';
            $scope.goodsId = goodsId;
            $http.get(api.getItemUrl, {
                params: {
                    goodsId: goodsId
                }
            }).success(function (res) {
                if (res.state) {

                    var data = res.data;
                    $scope.detail.goodsName = data.goodsName;
                    $scope.detail.description = data.description;
                    $scope.detail.categoryId = data.categoryId;
                    $scope.detail.price = data.price;
                    $scope.detail.stock = data.stock;
                    $scope.detail.liveUrl = data.liveUrl;
                    $scope.detail.thumb = data.thumb;
                    $scope.detail.bannerThumb = data.bannerThumb;
                    $scope.detail.recommendThumb = data.recommendThumb;
                    $scope.detail.unit = data.unit;
                    $scope.detail.stars = data.stars;
                    $scope.detail.expType = parseInt(data.expType);
                    $scope.detail.expAmount = data.expAmount;
                    $scope.detail.activity = data.activity == "on" ? true : false;
                    $scope.selectExpType = $scope.detail.expType;

                    $scope.thumbView = data.fullPath;
                    $scope.recommendThumbView = data.recommendFullPath;
                    $scope.bannerThumbView = data.bannerFullPath;

                    ue.ready(function () {
                        ue.setContent(data.content);
                    });

                    angular.forEach(data.rules, function (val) {
                        $scope.rules.push({
                            id: val.id,
                            ruleName: val.name,
                            ruleStore: val.stock,
                            ruleOldPrice: val.oldPrice,
                            ruleNewPrice: val.salePrice,
                            rulePurchaserPrice: val.purchaserPrice,
                            ruleGoodsWeight: val.weight,
                            ruleExpressWeight: val.expressWeight
                        })
                    });

                    angular.forEach(data.thumbLists, function (val) {
                        $scope.thumbLists.push({
                            id: val.id,
                            key: val.thumb,
                            thumb: val.thumb_view
                        });
                    });

                }
            });

        }

        // 物流类型
        $scope.expType = function(type) {
            $scope.selectExpType = type;
            $scope.detail.expType = type;
        };

        $scope.setStar = function (s) {
            $scope.detail.stars = s;
        };

        // =============================================
        // 初始化Web Uploader
        var uploader = WebUploader.create({
            auto: true,
            server: '/general/general/upload?width=320&height=180',
            pick: '#uploadImage',
            duplicate: true,
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,png'
            }
        });

        uploader.on( 'uploadSuccess', function(file, res) {
            if (res.state) {
                $scope.detail.thumb = res.data.key;
                $scope.detail.thumbWidth = res.data.data.width;
                $scope.detail.thumbHeight = res.data.data.height;
                var b = res.data.fullPath;
                $scope.thumbView = b || '';
                $scope.$apply();
            } else {
                var error = res.error ? res.error : '上传失败';
                Modal.error(error);
            }
        });

        /**
         * 删除
         * @param index
         * @returns {boolean}
         */
        $scope.removeThumb = function (index) {
            if ($scope.thumbLists.length == 0) {
                return false;
            }

            $scope.thumbLists.splice(index, 1);
        };

        $scope.clearAll = function () {
            $scope.thumbLists = [];
        };


        $scope.addRule = function () {
            $('#videoModal').modal();
        };

        $scope.addRuleItem = function () {
            var data = $scope.ruleItem;
            if (!data.ruleName || !data.ruleNewPrice || !data.ruleStore || !data.ruleOldPrice || !data.rulePurchaserPrice) {
                return false;
            }
            $scope.rules.push(data);
            $scope.ruleItem = angular.copy(ruleBak);
            $('#videoModal').modal('hide');
        };

        $scope.removeRuleItem = function (index) {
            $scope.rules.splice(index, 1);
        };
        // ===========end==================================

        $scope.save = function () {

            var params = $scope.detail;
            params['content'] = ue.getContent();

            if (params['expType'] == 2 && params['expAmount'] !== null) {
                params['expAmount'] = parseInt(params['expAmount'] * 100);
            } else if (params['expType'] == 1) {
                params['expAmount'] = 0;
            } else {
                Modal.alert({
                    title: '邮费设置提示',
                    content: '如果商品设置免邮,请手动填写0元'
                });
                return false;
            }

            if (!checkParams(params)) {
                return false;
            }

            // 规格
            if (!$scope.rules || $scope.rules.length == 0) {
                Modal.alert('请配置商品规格');
                return false;
            } else {
                var rules = [];
                angular.forEach($scope.rules, function (val) {
                    rules.push({
                        id: val.id,
                        ruleName: val.ruleName,
                        ruleStore: val.ruleStore,
                        ruleOldPrice: val.ruleOldPrice,
                        ruleNewPrice: val.ruleNewPrice,
                        rulePurchaserPrice: val.rulePurchaserPrice,
                        ruleGoodsWeight: val.ruleGoodsWeight,
                        ruleExpressWeight: val.ruleExpressWeight
                    })
                });
                params['rules'] = rules;
            }

            // 缩略图
            if (!$scope.thumbLists || $scope.thumbLists.length == 0) {
                Modal.alert('请上传商品图片');
                return false;
            } else {
                var thumbs = [];
                angular.forEach($scope.thumbLists, function (val) {
                    thumbs.push({
                        id: val.id,
                        key: val['key']
                    });
                });
                params['thumbLists'] = thumbs;
            }

            var url = api.saveUrl;
            if ($scope.pageType == 'edit') {
                var url = api.editUrl;
                if (!$scope.goodsId) {
                    return false;
                }
                params['goodsId'] = $scope.goodsId;
            }

            params['activity'] = $scope.detail.activity ? "on" : "off";

            $http.post(url, params).success(function (res) {
                if (res.state) {
                    if ($scope.pageType == 'add') {
                        afterSave();
                    } else {
                       Modal.success('修改成功');
                    }
                } else {
                    var action = $scope.pageType == 'add' ? '添加' : '修改';
                    var err = res.error ? res.error : action + '失败';
                }
            });

        };

        function afterSave() {
            Modal.success({
                title: '商品添加成功',
                buttons: [{
                    'name': '返回列表',
                    'event': function () {
                        window.history.back();
                    }
                }, {
                    'name': '继续添加',
                    'event': function () {
                        $scope.detail = angular.copy(bak);
                        $scope.stream = angular.copy(streamBak);
                        $scope.thumbView = "";
                        $scope.selectVideo = false;
                        ue.setContent('');
                    }
                }]
            });
        }

        /**
         * 验证参数
         * @param params
         * @returns {boolean}
         */
        function checkParams(params) {

            if (!params.goodsName) {
                Modal.alert('商品名称不能为空');
                return false;
            }

            if (!params.categoryId) {
                Modal.alert('请选择分类');
                return false;
            }

            if (!params.content) {
                Modal.alert('内容不能为空');
                return false;
            }

            return true;
        }

        function upload() {
            // 初始化Web Uploader
            var uploader = WebUploader.create({
                auto: true,
                server: '/system/upload/up',
                pick: '#addGoodsPic1',
                swf: '/assets/library/webuploader/Uploader.swf',
                duplicate: true,
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,png'
                }
            });

            // 成功
            uploader.on('uploadSuccess', function(file, res) {
                if (res.state) {
                    var data = {
                        key: res.data.key,
                        thumb: res.data.thumb
                    };
                    $scope.thumbLists.push(data);
                    upload2();
                } else {
                    var error = res.error ? res.error : '上传失败';
                    Modal.error(error);
                }
            });

            uploader.on('uploadComplete', function( file ) {
                $scope.$apply();
                delete uploader;
                upload();
            });
        }
        upload();

        function upload2() {
            // 初始化Web Uploader
            var uploader = WebUploader.create({
                auto: true,
                server: '/system/upload/up',
                pick: '#addGoodsPic2',
                swf: '/assets/library/webuploader/Uploader.swf',
                duplicate: true,
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,png'
                }
            });

            // 成功
            uploader.on('uploadSuccess', function(file, res) {
                if (res.state) {
                    var data = {
                        key: res.data.key,
                        thumb: res.data.thumb
                    };
                    $scope.thumbLists.push(data);
                } else {
                    var error = res.error ? res.error : '上传失败';
                    Modal.error(error);
                }
            });

            uploader.on('uploadComplete', function( file ) {
                $scope.$apply();
                delete uploader;
                upload2();
            });
        }

        if (GetQueryString('goodsId') > 0) {
            upload2();
        }


    }]);


})();